package com.example.administrator.hqq.activity.module;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.hqq.MainActivity;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.NoScrollViewPager;
import com.example.administrator.hqq.adapter.FragmentsAdapter;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.AllModuleTopicBean;
import com.example.administrator.hqq.bean.ConventionListBean;
import com.example.administrator.hqq.bean.RegisterBeen;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.fragment.module.AddModuleClassifyFragment;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.google.gson.Gson;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import q.rorbin.verticaltablayout.VerticalTabLayout;
import q.rorbin.verticaltablayout.adapter.TabAdapter;
import q.rorbin.verticaltablayout.widget.ITabView;
import q.rorbin.verticaltablayout.widget.QTabView;
import q.rorbin.verticaltablayout.widget.TabView;

/**
 * 注册添加模块页面
 */
public class AddModuleActivity extends MyActivity {

    @BindView(R.id.finish)
    AutoLinearLayout finish;
    @BindView(R.id.add_module_search)
    Button addModuleSearch;
    @BindView(R.id.tablayout)
    VerticalTabLayout tablayout;
    @BindView(R.id.add_module_vp)
    NoScrollViewPager addModuleVp;
    @BindView(R.id.start)
    TextView start;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.confirm)
    TextView confirm;
    @BindView(R.id.add_module)
    AutoRelativeLayout addModule;
    @BindView(R.id.add_module_guide)
    ImageView addModuleGuide;
    private List<String> titles;
    private List<Fragment> fragments;
    private String TAG = this.getClass().getSimpleName();
    private FragmentsAdapter fragmentsAdapter;
    private TabAdapter tabAdapter;
    //选择的模块的id
    private List<String> topicIds;
    private Type type;
    private List<ConventionListBean.DataBean> data;
    private String category_id;
    private AllModuleTopicBean allModuleTopicBean;

    public static enum Type {
        REGISTER, MODIFICATION
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_module);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initview();
        initdata();
    }

    private void initdata() {
        OkHttpUtils.get().url(UrlFactory.getAllTopic())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                Gson gson = new Gson();
                allModuleTopicBean = gson.fromJson(response, AllModuleTopicBean.class);
                if (allModuleTopicBean.getCode() == 200) {
                    titles.clear();
                    for (int i = 0; i < allModuleTopicBean.getData().size(); i++) {
                        titles.add(allModuleTopicBean.getData().get(i).getCategory_name());
                        fragments.add(new AddModuleClassifyFragment(allModuleTopicBean.getData().get(i).getTopic(), i));
                        //设置每个模块的点击事件
                        ((AddModuleClassifyFragment) fragments.get(i)).setSelectModule(new AddModuleClassifyFragment.SelectModule() {
                            @Override
                            public void selectModule(int position, int childPosition) {
                                if (allModuleTopicBean.getData().get(position).getTopic().get(childPosition).isSelect()) {
                                    topicIds.add(allModuleTopicBean.getData().get(position).getTopic().get(childPosition).getId());
                                } else {
                                    topicIds.remove(allModuleTopicBean.getData().get(position).getTopic().get(childPosition).getId());
                                }
                                if (topicIds != null && topicIds.size() > 0) {
                                    number.setText("已选择" + topicIds.size() + "个兴趣");
                                    confirm.setVisibility(View.VISIBLE);
                                    number.setVisibility(View.VISIBLE);
                                    start.setSelected(true);
                                    start.setText("");
                                } else {
                                    number.setText("已选择" + topicIds.size() + "个兴趣");
                                    confirm.setVisibility(View.GONE);
                                    number.setVisibility(View.GONE);
                                    start.setSelected(false);
                                    start.setText("请选择兴趣模块");
                                }
                                //设置标记
                                int badgeNum = 0;
                                for (AllModuleTopicBean.DataBean.TopicBean topicBean : allModuleTopicBean.getData().get(position).getTopic()) {
                                    if (topicBean.isSelect()) {
                                        badgeNum++;
                                    }
                                }
                                tablayout.setTabBadge(position, badgeNum);
                                tablayout.getTabAt(position).getBadgeView().setShowShadow(false);
                                tablayout.getTabAt(position).getBadgeView().setBadgeBackgroundColor(Color.RED);
                            }
                        });
                    }
                    setAdapter(allModuleTopicBean);
                }
            }
        });
    }

    /**
     * 设置以及选中的模块
     *
     * @param allModuleTopicBean
     */
    private void PitchOnModule(AllModuleTopicBean allModuleTopicBean) {
        for (int i = 0; i < allModuleTopicBean.getData().size(); i++) {
            int num = 0;
            for (AllModuleTopicBean.DataBean.TopicBean topicBean : allModuleTopicBean.getData().get(i).getTopic()) {
                topicBean.setSelect(false);
                for (String datum : topicIds) {
                    if (datum.equals(topicBean.getId())) {
                        topicBean.setSelect(true);
                        num++;
                    }
                }
            }
            if (tablayout.getTabAt(i).getBadgeView() != null) {
                tablayout.setTabBadge(i, num);
                tablayout.getTabAt(i).getBadgeView().setShowShadow(false);
                tablayout.getTabAt(i).getBadgeView().setBadgeBackgroundColor(Color.RED);
            }
        }
    }

    private void setAdapter(AllModuleTopicBean allModuleTopicBean) {
        addModuleVp.setOffscreenPageLimit(fragments.size());
        fragmentsAdapter = new FragmentsAdapter(getSupportFragmentManager(), fragments);
        addModuleVp.setAdapter(fragmentsAdapter);
        tablayout.setupWithViewPager(addModuleVp);
        tablayout.setTabAdapter(new TabAdapter() {
            @Override
            public int getCount() {
                return titles.size();
            }

            @Override
            public TabView.TabBadge getBadge(int position) {
                return new QTabView.TabBadge.Builder()
                        .setBackgroundColor(R.color.green_d9f0eb)
                        .build();
            }

            @Override
            public QTabView.TabIcon getIcon(int position) {
                return new QTabView.TabIcon.Builder()
                        .setIcon(R.color.gray_fdf6ef, R.color.green_d9f0eb)
                        .build();
            }

            @Override
            public QTabView.TabTitle getTitle(int position) {
                return new QTabView.TabTitle.Builder()
                        .setContent(titles.get(position))
                        .setTextColor(Color.BLACK, Color.BLACK)
                        .build();
            }

            @Override
            public int getBackground(int position) {
                return 0;
            }
        });
        switch (type) {
            case MODIFICATION:
                //设置选择的模块
                PitchOnModule(allModuleTopicBean);
                break;
            case REGISTER:
                PitchOnModule(allModuleTopicBean);
                break;
        }
        if (!TextUtils.isEmpty(category_id)) {
            for (int i = 0; i < allModuleTopicBean.getData().size(); i++) {
                if (category_id.equals(allModuleTopicBean.getData().get(i).getCategory_id())) {
                    tablayout.setTabSelected(i);
                }
            }
        }
    }

    private void initview() {
        //设置侧拉tablayout
        fragments = new ArrayList<>();
        titles = new ArrayList<>();
        topicIds = new ArrayList<>();
        type = (Type) getIntent().getSerializableExtra(LoongsConfig.type);
        category_id = getIntent().getStringExtra(LoongsConfig.category_id);
        data = (List<ConventionListBean.DataBean>) getIntent().getSerializableExtra(LoongsConfig.data);
        if (type != null) {
            switch (type) {
                case REGISTER:
                    addModule.setVisibility(View.INVISIBLE);
                    List<String> hobbies = (List<String>) getIntent().getSerializableExtra(LoongsConfig.hobbies);
                    if (hobbies != null && hobbies.size() > 0) {
                        for (String hobby : hobbies) {
                            topicIds.add(hobby);
                        }
                        number.setText("已选择" + topicIds.size() + "个兴趣");
                        confirm.setVisibility(View.VISIBLE);
                        number.setVisibility(View.VISIBLE);
                        start.setSelected(true);
                        start.setText("");
                    }
                    break;
                case MODIFICATION:
                    boolean aBoolean = SPUtils.getInstance().getBoolean(LoongsConfig.creat_module, true);
                    if (aBoolean) {
                        addModuleGuide.setVisibility(View.VISIBLE);
                        SPUtils.getInstance().put(LoongsConfig.creat_module, false);
                    }
                    //修改模块的逻辑
                    if (data != null) {
                        for (ConventionListBean.DataBean datum : data) {
                            topicIds.add(datum.getId());
                        }
                    }
                    number.setText("已选择" + topicIds.size() + "个兴趣");
                    confirm.setVisibility(View.VISIBLE);
                    number.setVisibility(View.VISIBLE);
                    start.setSelected(true);
                    start.setText("");
                    break;
            }
        }

    }

    @OnClick({R.id.add_module_guide,R.id.finish, R.id.add_module_search, R.id.confirm, R.id.add_module})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_module_guide:
                addModuleGuide.setVisibility(View.GONE);
                break;
            case R.id.finish:
                finish();
                break;
            case R.id.add_module_search:
                Intent intent = new Intent(this, SearchModuleActivity.class);
                intent.putExtra(LoongsConfig.topicIds, (Serializable) topicIds);
                intent.putExtra(LoongsConfig.type,getIntent().getSerializableExtra(LoongsConfig.type));
                startActivityForResult(intent, 120);
                break;
            case R.id.confirm:
                switch (type) {
                    case REGISTER:
                        register();
                        break;
                    case MODIFICATION:
                        modificationModule();
                        break;
                }
                break;
            case R.id.add_module:
                Intent intent1 = new Intent(this, ApplyForNewModuleActivity.class);
                startActivity(intent1);
                break;
        }
    }

    /**
     * 修改首页常规模块内容
     */
    private void modificationModule() {
        if (topicIds != null && topicIds.size() != 0) {
            showLoadingDialog();
            String s = "";
            for (String topicId : topicIds) {
                if (topicId.equals(topicIds.get(topicIds.size() - 1))) {
                    s += topicId;
                    break;
                }
                s += topicId + ",";
            }
            OkHttpUtils.get().url(UrlFactory.UserTopicBulkTopic())
                    .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                    .addParams(LoongsConfig.topic_id, s)
                    .build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.e(TAG, "onError: " + e.getMessage());
                    dismissLoadingDialog();
                }

                @Override
                public void onResponse(String response, int id) {
                    dismissLoadingDialog();
                    Log.e(TAG, "onResponse: " + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.getInt(LoongsConfig.code) == 200) {
                            EventBus.getDefault().post("更新常规模块");
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 用户注册
     */
    private void register() {
        String topic = "";
        for (String topicId : topicIds) {
            if (topicId.equals(topicIds.get(topicIds.size() - 1))) {
                topic += topicId;
                break;
            }
            topic += topicId + ",";
        }
        GetBuilder tag = OkHttpUtils.get().url(UrlFactory.register()).tag(this);
        Log.e(TAG, "onViewClicked: " + getIntent().getStringExtra(LoongsConfig.phone));
        tag.addParams(LoongsConfig.phone, getIntent().getStringExtra(LoongsConfig.phone))
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.nickname, getIntent().getStringExtra(LoongsConfig.user_name))
                .addParams(LoongsConfig.birth, getIntent().getStringExtra(LoongsConfig.birth))
                .addParams(LoongsConfig.gender, getIntent().getStringExtra(LoongsConfig.sex))
                .addParams(LoongsConfig.portrait_id, getIntent().getStringExtra(LoongsConfig.url))
                .addParams(LoongsConfig.topic, topic)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "注册onError: " + e.getMessage());
                ToastUtils.showShort("注册失败请稍后重试");
            }

            @Override
            public void onResponse(String s, int id) {
                Log.e(TAG, "注册onResponse: " + s);
                Gson gson = new Gson();
                RegisterBeen registerBeen = gson.fromJson(s, RegisterBeen.class);
                HintWordsUtils.showMarkeWords(registerBeen.getCode(),registerBeen.getDescription());
                if (registerBeen.getCode() == 200) {
                    String login_token = registerBeen.getLogin_token();
                    String rongyun_token = registerBeen.getRongyun_token();
                    String gender = registerBeen.getGender();
                    SPUtils.getInstance().put(LoongsConfig.gender, gender);
                    SPUtils.getInstance().put(LoongsConfig.loginToken, login_token);
                    SPUtils.getInstance().put(LoongsConfig.rongToken, rongyun_token);
                    Intent intent = new Intent(AddModuleActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 120 && resultCode == 122) {
            topicIds.clear();
            topicIds.addAll((List<String>) data.getSerializableExtra(LoongsConfig.topicIds));
            number.setText("已选择" + topicIds.size() + "个兴趣");
            confirm.setVisibility(View.VISIBLE);
            number.setVisibility(View.VISIBLE);
            start.setSelected(true);
            start.setText("");
            //设置选择的模块
            PitchOnModule(allModuleTopicBean);
            if (fragments.size() > 0)
                ((AddModuleClassifyFragment) fragments.get(0)).notifyDataSetChanged();
            for (int i = 0; i < fragments.size(); i++) {
                ((AddModuleClassifyFragment) fragments.get(i)).notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        fragments.clear();
        fragments = null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(String s) {

    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }
}
